package com.lst.api.service.impl;

import com.lst.api.entity.FileUpload;
import com.lst.api.mapper.FileUploadMapper;
import com.lst.api.service.IFileUploadService;
import com.lst.tools.basics.utils.IoUtils;
import com.lst.tools.mybatis.service.impl.BaseService;
import com.lst.tools.oss.OssUtils;
import com.lst.tools.oss.exception.OssUploadException;
import com.lst.tools.oss.service.IOssService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件上传记录表业务层实现
 *
 * @author Allen
 * @date 2019-09-30 15:33:59
 * @version: V1.0
 */
@Service
public class FileUploadService extends BaseService<FileUploadMapper, FileUpload> implements IFileUploadService {

    private static final String ROOT_FOLDER = "lst";

    @Autowired
    private IOssService ossService;

    @Override
    public String fileUpload(long userId, String folderName, String originName, String format, InputStream inputStream) throws Exception {
        if (inputStream == null || StringUtils.isAllBlank(folderName, originName)) {
            return null;
        }
        String staticKey = OssUtils.getStaticKey(ROOT_FOLDER, userId, format, folderName);
        Long size = Long.valueOf(inputStream.available());
        String key = fileUpload(staticKey, inputStream);
        if (StringUtils.isBlank(key)) {
            throw new OssUploadException("上传失败！");
        }
        FileUpload fileUpload = new FileUpload();
        fileUpload.setSourceUserId(userId);
        fileUpload.setBizeType(folderName);
        fileUpload.setOriginName(originName);
        fileUpload.setNewName(OssUtils.getFileNameByKey(key));
        fileUpload.setPath(staticKey);
        fileUpload.setFormat(format);
        fileUpload.setSize(size);
        super.save(fileUpload);
        return key;
    }

    private String fileUpload(String staticKey, InputStream inputStream) throws Exception {
        OutputStream outputStream = null;
        try {
            staticKey = ossService.put(staticKey, inputStream);
            return StringUtils.isBlank(staticKey) ? null : ossService.getOssUrl(staticKey);
        } finally {
            IoUtils.close(inputStream, outputStream);
        }
    }
}